package com.banquetmanagementsystem.common.Utils;

import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Random;
/**
 *
 * @author 86176
 */
@Component
public class CaptchaUtil {
    private static final int MAX_ALPHABET_LETTERS =26;
    private static final int MAX_NUMBERS = 10;
    private static final int CODE_LENGTH=5;
    private static final int FORTY=40;

    /**
     * 获取一个随机颜色
     * @return 返回随机Color对象
     */
    public Color getColor() {
        Random rand = new Random();
        int r = rand.nextInt(256);
        int g = rand.nextInt(256);
        int b = rand.nextInt(256);
        return new Color(r, g, b);
    }

    /**
     * 获取一个长度为5的随机验证码
     * @return 返回随机验证码
     */
    public String getCode() {
        ArrayList<Character> list = new ArrayList<>(36);
        for (int i = 0; i < MAX_ALPHABET_LETTERS; i++) {
            list.add((char) ('a' + i));
            list.add((char) ('A' + i));
        }
        for (int i = 0; i < MAX_NUMBERS; i++) {
            list.add((char) ('0' + i));
        }
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = r.nextInt(list.size());
            char c = list.get(index);
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 获取验证码图片的base64字符串
     * @param code 验证码
     * @return base64字符串
     */
    public String getBase64(String code) {
        //创建一个画布
        BufferedImage bImage = new BufferedImage(93, 40, BufferedImage.TYPE_INT_RGB);
        //创建一个画笔
        Graphics graphics = bImage.createGraphics();
        //选择填充的区域
        graphics.fillRect(0, 0, 93, 40);
        for (int i = 0; i <= FORTY; i++) {
            Random rand = new Random();
            int xB = rand.nextInt(93);
            int yB = rand.nextInt(40);
            int xE = rand.nextInt(xB + 10);
            int yE = rand.nextInt(yB + 10);
            graphics.setColor(getColor());
            graphics.drawLine(xB, yB, xE, yE);
        }
        graphics.setFont(new Font("Serif", Font.BOLD, 25));
        System.out.println(code);
        for (int i = 0; i < code.length(); i++) {
            graphics.setColor(getColor());
            graphics.drawString(Character.toString(code.charAt(i)), 10+i*15, 25);
        }

        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(bImage, "png", byteArrayOutputStream);
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
